package farmers.yavtube.util;

import lombok.SneakyThrows;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author hongliang.dinghl Dom4j 生成XML文档与解析XML文档
 */
public class MyThread implements Runnable {

	private String imgSrc;	// 远程图片地址
	private String filePath;	// 本地文件夹
	private String fileName;	// 本地文件

	private final int fileSize = 30 * 1024;	// 下载文件，小于x删除

	private boolean openIE = false;	// 打開IE
	private static int maxPic = 1;	// IE开次数

	public MyThread(String imgSrc, String filePath, String fileName) {
		super();
		this.imgSrc = imgSrc;
		this.filePath = filePath;
		this.fileName = fileName;
	}

	@SneakyThrows
	@Override
	public void run() {
		if (this.imgExists()) {
			return;
		}

		try {
			System.out.println(filePath + fileName + "\t" + imgSrc + "\t开始下载");
			this.downloadImgByNet(imgSrc, filePath, fileName);
			File file = new File(filePath + File.separator + fileName);
			double file_kb = file.length() / 1024;
//			System.out.println("file:///" + file.getAbsolutePath().replaceAll("\\\\", "/") + "\t" + imgSrc + "\t下载成功\t" + file_kb + "KB");
			 System.out.println(filePath + fileName + "\t" + imgSrc + "\t下载成功\t" + file_kb + "KB");
			this.imgExists();	// 删除不符合大小的图片
		} catch (Exception e) {
			String errorMessage = e.getMessage();
			if(errorMessage.contains("Server returned HTTP response code: 523")){
				return;
			}

			System.out.println(filePath + fileName + "\t下载失败 " + errorMessage + "\t" + imgSrc);
			if(openIE && maxPic > 0){
				Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + imgSrc);
				maxPic--;
			}
		}
	}
//	{
//		// 指定IE路径方式来打开网址
//		String iepath1 = "C:\\Program Files\\Internet Explorer\\iexplore.exe";
//		String iepath2 = "C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";
//		final Runtime runtime = Runtime.getRuntime();
//		Process process = null;
//		File file = new File(iepath1);
//		if(file.exists()) {
//			process = runtime.exec(iepath1+" " + sb.toString());
//		} else {
//			File file2 = new File(iepath2);
//			process = runtime.exec(iepath2+" " + sb.toString());
//		}
//	}
	// 判断图片是否生成 true=生成 false=不生成
	public boolean imgExists() {
		File file = new File(filePath + File.separator + fileName);

		// 存在文件
		if (file.exists()) {
			// 文件小于 30kb
			if (file.length() < fileSize) {
				file.delete();
				return true;
			}
		} else {
			return false;
		}

		return true;
	}

	/**
	 * 抓取网上的图片
	 * 
	 * @param imgSrc
	 * @param filePath
	 */
	public void downloadImgByNet(String imgSrc, String filePath, String fileName) throws Exception{
		URL url = new URL(imgSrc);
		URLConnection conn = url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(10 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		// 输出流
		InputStream str = conn.getInputStream();
		// 控制流的大小为1k
		byte[] bs = new byte[10240];
		// 读取到的长度
		int len = 0;

		// 是否需要创建文件夹
		File saveDir = new File(filePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		File file = new File(saveDir + File.separator + fileName);

		// 实例输出一个对象
		FileOutputStream out = new FileOutputStream(file);
		// 循环判断，如果读取的个数b为空了，则is.read()方法返回-1，具体请参考InputStream的read();
		while ((len = str.read(bs)) != -1) {
			// 将对象写入到对应的文件中
			out.write(bs, 0, len);
		}
		// 刷新流
		out.flush();
		// 关闭流
		out.close();
		str.close();
	}

}